//
//  BCQrScaningController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2019/1/14.
//  Copyright © 2019 guoshikeji. All rights reserved.
//

#import "BCQrScaningController.h"

#import "SGQRCode.h"

#import "UIAlertController+Authorization.h"

//
#import "BCValidateAddressRequest.h"

@interface BCQrScaningController () <SGQRCodeScanManagerDelegate>

@property (nonatomic, strong) SGQRCodeScanningView *scanningView;


/**
 *initScanningFlag 第一次进入后启动扫描的flag
 */
@property (nonatomic, assign) BOOL initScanningFlag;

@end

@implementation BCQrScaningController

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.view.backgroundColor = [UIColor blackColor];
    //
    [self setupSubviews];
    //
}
- (void)setupSubviews {
    self.customNaviBar.backgroundColor = [UIColor clearColor];
    //设置
    [SGQRCodeScanManager sharedManager].delegate = self;
    //
    self.scanningView = [[SGQRCodeScanningView alloc] initWithFrame:self.view.bounds layer:self.view.layer];
    [self.view addSubview:self.scanningView];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //
    if (!self.initScanningFlag) {
        self.initScanningFlag = true;
        NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];//读取设备授权状态
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){//权限没开启
            [UIAlertController showCameraAuthorizationWithController:self];
        }else {
            [self startScanning];
        }
    }
}


- (void)startScanning {
    [[SGQRCodeScanManager sharedManager] SG_videoPreviewLayerRemoveFromSuperlayer];
    //
    NSArray *metadataObjectTypes = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code,  AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    [[SGQRCodeScanManager sharedManager] SG_setupSessionPreset:AVCaptureSessionPresetHigh metadataObjectTypes:metadataObjectTypes currentController:self];
    [self.view bringSubviewToFront:self.scanningView];
    [self.scanningView addTimer];
    [[SGQRCodeScanManager sharedManager] SG_startRunning];
    //
    [self.view bringSubviewToFront:self.customNaviBar];
}
- (void)stopScanning {
    [self.scanningView removeTimer];
    [[SGQRCodeScanManager sharedManager] SG_stopRunning];
}




#pragma mark - SGQRCodeScanManagerDelegate
/// 二维码扫描获取数据的回调方法 (metadataObjects: 扫描二维码数据信息)
- (void)QRCodeScanManager:(SGQRCodeScanManager *)scanManager didOutputMetadataObjects:(NSArray *)metadataObjects {
    if (metadataObjects.count) {
        [self stopScanning];
        AVMetadataMachineReadableCodeObject *obj = metadataObjects.firstObject;
        if (obj.stringValue.length) {
            [self requestValidate:obj.stringValue];
        }
    }
}
//校验
- (void)requestValidate:(NSString *)address {
    [self.view bc_showActivityIndicatorBackgroundColor:[UIColor clearColor] insets:UIEdgeInsetsZero activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    //
    BCValidateAddressRequest *request = [BCValidateAddressRequest new];
    request.addr = address;
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.view bc_hiddenActivityIndicator];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCValidateAddressResponse *resp = result;
        if (resp.data.isvalid) {
            [wself completeScanningWithStringValue:request.addr];
        }else {
            [wself showErrorTitle:BCLocalizedKey(@"The address is invalid") message:request.addr];
        }
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error) {
            [wself showErrorTitle:error.domain message:request.addr];
        }
    }];
    [request requestServer];
}

- (void)showErrorTitle:(NSString *)title message:(NSString *)message {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    //
    WEAK_SELF
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [wself.navigationController popViewControllerAnimated:true];
    }];
    [alertVC addAction:cancelAction];
    UIAlertAction *scanningAction = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Scanning Again") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself startScanning];
    }];
    [alertVC addAction:scanningAction];
    //
    [self.navigationController presentViewController:alertVC animated:true completion:nil];
}
//- (void)



- (void)completeScanningWithStringValue:(NSString *)stringValue {
    if (stringValue.length) {
        WEAK_SELF
        NSString *title = BCLocalizedKey(@"The address is valid");
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:stringValue preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *done = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Sure") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (wself.delegate && [wself.delegate respondsToSelector:@selector(qrScanningControllerCompleteScanningWithStringValue:)]) {
                [wself.delegate qrScanningControllerCompleteScanningWithStringValue:stringValue];
                //
                [wself.navigationController popViewControllerAnimated:true];
            }
        }];
        [alertVC addAction:done];
        [self.navigationController presentViewController:alertVC animated:true completion:nil];
    }
}



- (void)dealloc {
    [self.scanningView removeTimer];
}

@end
